home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / json / encoder.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  12KB  |  414 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Implementation of JSONEncoder
  5. '''
  6. import re
  7. import math
  8.  
  9. try:
  10.     from _json import encode_basestring_ascii as c_encode_basestring_ascii
  11. except ImportError:
  12.     c_encode_basestring_ascii = None
  13.  
  14. __all__ = [
  15.     'JSONEncoder']
  16. ESCAPE = re.compile('[\\x00-\\x1f\\\\"\\b\\f\\n\\r\\t]')
  17. ESCAPE_ASCII = re.compile('([\\\\"]|[^\\ -~])')
  18. HAS_UTF8 = re.compile('[\\x80-\\xff]')
  19. ESCAPE_DCT = {
  20.     '\\': '\\\\',
  21.     '"': '\\"',
  22.     '\x08': '\\b',
  23.     '\x0c': '\\f',
  24.     '\n': '\\n',
  25.     '\r': '\\r',
  26.     '\t': '\\t' }
  27. for i in range(32):
  28.     ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
  29.  
  30. FLOAT_REPR = repr
  31.  
  32. def floatstr(o, allow_nan = True):
  33.     if math.isnan(o):
  34.         text = 'NaN'
  35.     elif math.isinf(o):
  36.         if math.copysign(1, o) == 1:
  37.             text = 'Infinity'
  38.         else:
  39.             text = '-Infinity'
  40.     else:
  41.         return FLOAT_REPR(o)
  42.     if not math.isnan(o):
  43.         msg = 'Out of range float values are not JSON compliant: ' + repr(o)
  44.         raise ValueError(msg)
  45.     math.isnan(o)
  46.     return text
  47.  
  48.  
  49. def encode_basestring(s):
  50.     '''Return a JSON representation of a Python string
  51.  
  52.     '''
  53.     
  54.     def replace(match):
  55.         return ESCAPE_DCT[match.group(0)]
  56.  
  57.     return '"' + ESCAPE.sub(replace, s) + '"'
  58.  
  59.  
  60. def py_encode_basestring_ascii(s):
  61.     if isinstance(s, str) and HAS_UTF8.search(s) is not None:
  62.         s = s.decode('utf-8')
  63.     
  64.     
  65.     def replace(match):
  66.         s = match.group(0)
  67.         
  68.         try:
  69.             return ESCAPE_DCT[s]
  70.         except KeyError:
  71.             n = ord(s)
  72.             if n < 65536:
  73.                 return '\\u{0:04x}'.format(n)
  74.             n -= 65536
  75.             s1 = 55296 | n >> 10 & 1023
  76.             s2 = 56320 | n & 1023
  77.             return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
  78.         except:
  79.             n < 65536
  80.  
  81.  
  82.     return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
  83.  
  84. if c_encode_basestring_ascii is not None:
  85.     encode_basestring_ascii = c_encode_basestring_ascii
  86. else:
  87.     encode_basestring_ascii = py_encode_basestring_ascii
  88.  
  89. class JSONEncoder(object):
  90.     '''Extensible JSON <http://json.org> encoder for Python data structures.
  91.  
  92.     Supports the following objects and types by default:
  93.  
  94.     +-------------------+---------------+
  95.     | Python            | JSON          |
  96.     +===================+===============+
  97.     | dict              | object        |
  98.     +-------------------+---------------+
  99.     | list, tuple       | array         |
  100.     +-------------------+---------------+
  101.     | str, unicode      | string        |
  102.     +-------------------+---------------+
  103.     | int, long, float  | number        |
  104.     +-------------------+---------------+
  105.     | True              | true          |
  106.     +-------------------+---------------+
  107.     | False             | false         |
  108.     +-------------------+---------------+
  109.     | None              | null          |
  110.     +-------------------+---------------+
  111.  
  112.     To extend this to recognize other objects, subclass and implement a
  113.     ``.default()`` method with another method that returns a serializable
  114.     object for ``o`` if possible, otherwise it should call the superclass
  115.     implementation (to raise ``TypeError``).
  116.  
  117.     '''
  118.     __all__ = [
  119.         '__init__',
  120.         'default',
  121.         'encode',
  122.         'iterencode']
  123.     item_separator = ', '
  124.     key_separator = ': '
  125.     
  126.     def __init__(self, skipkeys = False, ensure_ascii = True, check_circular = True, allow_nan = True, sort_keys = False, indent = None, separators = None, encoding = 'utf-8', default = None):
  127.         """Constructor for JSONEncoder, with sensible defaults.
  128.  
  129.         If skipkeys is False, then it is a TypeError to attempt
  130.         encoding of keys that are not str, int, long, float or None.  If
  131.         skipkeys is True, such items are simply skipped.
  132.  
  133.         If ensure_ascii is True, the output is guaranteed to be str
  134.         objects with all incoming unicode characters escaped.  If
  135.         ensure_ascii is false, the output will be unicode object.
  136.  
  137.         If check_circular is True, then lists, dicts, and custom encoded
  138.         objects will be checked for circular references during encoding to
  139.         prevent an infinite recursion (which would cause an OverflowError).
  140.         Otherwise, no such check takes place.
  141.  
  142.         If allow_nan is True, then NaN, Infinity, and -Infinity will be
  143.         encoded as such.  This behavior is not JSON specification compliant,
  144.         but is consistent with most JavaScript based encoders and decoders.
  145.         Otherwise, it will be a ValueError to encode such floats.
  146.  
  147.         If sort_keys is True, then the output of dictionaries will be
  148.         sorted by key; this is useful for regression tests to ensure
  149.         that JSON serializations can be compared on a day-to-day basis.
  150.  
  151.         If indent is a non-negative integer, then JSON array
  152.         elements and object members will be pretty-printed with that
  153.         indent level.  An indent level of 0 will only insert newlines.
  154.         None is the most compact representation.
  155.  
  156.         If specified, separators should be a (item_separator, key_separator)
  157.         tuple.  The default is (', ', ': ').  To get the most compact JSON
  158.         representation you should specify (',', ':') to eliminate whitespace.
  159.  
  160.         If specified, default is a function that gets called for objects
  161.         that can't otherwise be serialized.  It should return a JSON encodable
  162.         version of the object or raise a ``TypeError``.
  163.  
  164.         If encoding is not None, then all input strings will be
  165.         transformed into unicode using that encoding prior to JSON-encoding.
  166.         The default is UTF-8.
  167.  
  168.         """
  169.         self.skipkeys = skipkeys
  170.         self.ensure_ascii = ensure_ascii
  171.         self.check_circular = check_circular
  172.         self.allow_nan = allow_nan
  173.         self.sort_keys = sort_keys
  174.         self.indent = indent
  175.         self.current_indent_level = 0
  176.         if separators is not None:
  177.             (self.item_separator, self.key_separator) = separators
  178.         
  179.         if default is not None:
  180.             self.default = default
  181.         
  182.         self.encoding = encoding
  183.  
  184.     
  185.     def _newline_indent(self):
  186.         return '\n' + ' ' * self.indent * self.current_indent_level
  187.  
  188.     
  189.     def _iterencode_list(self, lst, markers = None):
  190.         if not lst:
  191.             yield '[]'
  192.             return None
  193.         if markers is not None:
  194.             markerid = id(lst)
  195.             if markerid in markers:
  196.                 raise ValueError('Circular reference detected')
  197.             markerid in markers
  198.             markers[markerid] = lst
  199.         
  200.         yield '['
  201.         if self.indent is not None:
  202.             self.current_indent_level += 1
  203.             newline_indent = self._newline_indent()
  204.             separator = self.item_separator + newline_indent
  205.             yield newline_indent
  206.             self
  207.         else:
  208.             newline_indent = None
  209.             separator = self.item_separator
  210.         first = True
  211.         for value in lst:
  212.             if first:
  213.                 first = False
  214.             else:
  215.                 yield separator
  216.             for chunk in self._iterencode(value, markers):
  217.                 yield chunk
  218.             
  219.         
  220.         if newline_indent is not None:
  221.             self.current_indent_level -= 1
  222.             yield self._newline_indent()
  223.             self
  224.         
  225.         yield ']'
  226.         if markers is not None:
  227.             del markers[markerid]
  228.         
  229.  
  230.     
  231.     def _iterencode_dict(self, dct, markers = None):
  232.         if not dct:
  233.             yield '{}'
  234.             return None
  235.         if markers is not None:
  236.             markerid = id(dct)
  237.             if markerid in markers:
  238.                 raise ValueError('Circular reference detected')
  239.             markerid in markers
  240.             markers[markerid] = dct
  241.         
  242.         yield '{'
  243.         key_separator = self.key_separator
  244.         if self.indent is not None:
  245.             self.current_indent_level += 1
  246.             newline_indent = self._newline_indent()
  247.             item_separator = self.item_separator + newline_indent
  248.             yield newline_indent
  249.             self
  250.         else:
  251.             newline_indent = None
  252.             item_separator = self.item_separator
  253.         first = True
  254.         if self.ensure_ascii:
  255.             encoder = encode_basestring_ascii
  256.         else:
  257.             encoder = encode_basestring
  258.         allow_nan = self.allow_nan
  259.         _encoding = self.encoding
  260.         if _encoding is not None:
  261.             pass
  262.         _do_decode = not (_encoding == 'utf-8')
  263.         for key, value in items:
  264.             if isinstance(key, str):
  265.                 if _do_decode:
  266.                     key = key.decode(_encoding)
  267.                 
  268.             elif isinstance(key, basestring):
  269.                 pass
  270.             elif isinstance(key, float):
  271.                 key = floatstr(key, allow_nan)
  272.             elif isinstance(key, (int, long)):
  273.                 key = str(key)
  274.             elif key is True:
  275.                 key = 'true'
  276.             elif key is False:
  277.                 key = 'false'
  278.             elif key is None:
  279.                 key = 'null'
  280.             elif self.skipkeys:
  281.                 continue
  282.             else:
  283.                 raise TypeError('key {0!r} is not a string'.format(key))
  284.             if None if self.sort_keys else []:
  285.                 first = False
  286.             else:
  287.                 yield item_separator
  288.             yield encoder(key)
  289.             yield key_separator
  290.             for chunk in self._iterencode(value, markers):
  291.                 yield chunk
  292.             
  293.         
  294.         if newline_indent is not None:
  295.             self.current_indent_level -= 1
  296.             yield self._newline_indent()
  297.             self
  298.         
  299.         yield '}'
  300.         if markers is not None:
  301.             del markers[markerid]
  302.         
  303.  
  304.     
  305.     def _iterencode(self, o, markers = None):
  306.         if isinstance(o, basestring):
  307.             if self.ensure_ascii:
  308.                 encoder = encode_basestring_ascii
  309.             else:
  310.                 encoder = encode_basestring
  311.             _encoding = self.encoding
  312.             if _encoding is not None and isinstance(o, str) and not (_encoding == 'utf-8'):
  313.                 o = o.decode(_encoding)
  314.             
  315.             yield encoder(o)
  316.         elif o is None:
  317.             yield 'null'
  318.         elif o is True:
  319.             yield 'true'
  320.         elif o is False:
  321.             yield 'false'
  322.         elif isinstance(o, (int, long)):
  323.             yield str(o)
  324.         elif isinstance(o, float):
  325.             yield floatstr(o, self.allow_nan)
  326.         elif isinstance(o, (list, tuple)):
  327.             for chunk in self._iterencode_list(o, markers):
  328.                 yield chunk
  329.             
  330.         elif isinstance(o, dict):
  331.             for chunk in self._iterencode_dict(o, markers):
  332.                 yield chunk
  333.             
  334.         elif markers is not None:
  335.             markerid = id(o)
  336.             if markerid in markers:
  337.                 raise ValueError('Circular reference detected')
  338.             markerid in markers
  339.             markers[markerid] = o
  340.         
  341.         for chunk in self._iterencode_default(o, markers):
  342.             yield chunk
  343.         
  344.         if markers is not None:
  345.             del markers[markerid]
  346.         
  347.  
  348.     
  349.     def _iterencode_default(self, o, markers = None):
  350.         newobj = self.default(o)
  351.         return self._iterencode(newobj, markers)
  352.  
  353.     
  354.     def default(self, o):
  355.         '''Implement this method in a subclass such that it returns a serializable
  356.         object for ``o``, or calls the base implementation (to raise a
  357.         ``TypeError``).
  358.  
  359.         For example, to support arbitrary iterators, you could implement
  360.         default like this::
  361.  
  362.             def default(self, o):
  363.                 try:
  364.                     iterable = iter(o)
  365.                 except TypeError:
  366.                     pass
  367.                 else:
  368.                     return list(iterable)
  369.                 return JSONEncoder.default(self, o)
  370.  
  371.         '''
  372.         raise TypeError(repr(o) + ' is not JSON serializable')
  373.  
  374.     
  375.     def encode(self, o):
  376.         '''Return a JSON string representation of a Python data structure.
  377.  
  378.         >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
  379.         \'{"foo": ["bar", "baz"]}\'
  380.  
  381.         '''
  382.         if isinstance(o, basestring):
  383.             if isinstance(o, str):
  384.                 _encoding = self.encoding
  385.                 if _encoding is not None and not (_encoding == 'utf-8'):
  386.                     o = o.decode(_encoding)
  387.                 
  388.             
  389.             if self.ensure_ascii:
  390.                 return encode_basestring_ascii(o)
  391.             return encode_basestring(o)
  392.         isinstance(o, basestring)
  393.         chunks = list(self.iterencode(o))
  394.         return ''.join(chunks)
  395.  
  396.     
  397.     def iterencode(self, o):
  398.         '''Encode the given object and yield each string representation as
  399.         available.
  400.  
  401.         For example::
  402.  
  403.             for chunk in JSONEncoder().iterencode(bigobject):
  404.                 mysocket.write(chunk)
  405.  
  406.         '''
  407.         if self.check_circular:
  408.             markers = { }
  409.         else:
  410.             markers = None
  411.         return self._iterencode(o, markers)
  412.  
  413.  
  414.